from flask import Blueprint, request, jsonify, g
from sqlalchemy import text

from decorators import login_required
from models import ProductModel, RecentlyTopProductsModel, AverageProductsModel, HistoricalTopProductsModel, \
    AlsUserRecsModel, ContentBasedProductRecs, ItemCFProductRecsModel

bp = Blueprint("offline", __name__, url_prefix="/offline")


# 近期热门推荐
@bp.route("/recentTop", methods=['POST'])
def getRecentTop():
    # 返回当前月的热门商品，开发阶段暂时使用2014-05
    # current_time = datetime.now().strftime("%Y-%m")
    current_time = "2014-05"
    data = request.get_json()
    page = int(data.get("page"))
    per_page = 12
    # 计算偏移量
    offset = (page - 1) * per_page

    # 根据要求条数获取到productIdList
    productIdList = list([term.product_id for term in RecentlyTopProductsModel.query.filter_by(year_month=current_time)
                         .order_by(-RecentlyTopProductsModel.product_count)])
    # 查询在productIdList中的商品信息
    products = ProductModel.query.filter(ProductModel.product_id.in_(productIdList)).limit(per_page).offset(
        offset).all()
    # 让products按productIdList的顺序
    sorted_products = sorted(products, key=lambda p: productIdList.index(p.product_id))
    # 获取总记录数
    total_records = ProductModel.query.filter(ProductModel.product_id.in_(productIdList)).count()
    # 转字典之后json
    productsList = [{k: v for k, v in product.__dict__.items() if k != '_sa_instance_state'} for product in
                    sorted_products]
    return jsonify({
        'total_pages': (total_records + per_page - 1) // per_page,
        'current_page': page,
        'productsList': productsList,
    })


# 历史热门推荐
@bp.route("/historicalTop", methods=['POST'])
def getHistoricalTop():
    # 获取参数
    data = request.get_json()
    page = int(data.get("page"))
    per_page = 12
    # 计算偏移量
    offset = (page - 1) * per_page

    productIdList = list([term.product_id for term in HistoricalTopProductsModel.query.all()])
    # 查询在productIdList中的商品信息
    products = ProductModel.query.filter(ProductModel.product_id.in_(productIdList)).limit(per_page).offset(
        offset).all()
    # 让products按productIdList的顺序
    sorted_products = sorted(products, key=lambda p: productIdList.index(p.product_id))
    # 获取总记录数
    total_records = ProductModel.query.filter(ProductModel.product_id.in_(productIdList)).count()
    # 转字典之后json
    productsList = [{k: v for k, v in product.__dict__.items() if k != '_sa_instance_state'} for product in
                    sorted_products]
    return jsonify({
        'total_pages': (total_records + per_page - 1) // per_page,  # 总记录数不是 per_page 的整数倍时，向上调整到能够整除 per_page 的最小整数
        'current_page': page,
        'productsList': productsList,
    })


# 好评榜推荐
@bp.route("/topRating", methods=['POST'])
def topRating():
    # 获取参数
    data = request.get_json()
    page = int(data.get("page"))
    per_page = 12
    # 计算偏移量
    offset = (page - 1) * per_page

    productIdList = [term.product_id for term in AverageProductsModel.query.filter().order_by(text('-product_rating'))]
    # 查询在productIdList中的商品信息
    products = ProductModel.query.filter(ProductModel.product_id.in_(productIdList)).limit(per_page).offset(
        offset).all()
    # 让products按productIdList的顺序
    sorted_products = sorted(products, key=lambda p: productIdList.index(p.product_id))
    # 获取总记录数
    total_records = ProductModel.query.filter(ProductModel.product_id.in_(productIdList)).count()
    # 转字典之后json
    productsList = [{k: v for k, v in product.__dict__.items() if k != '_sa_instance_state'} for product in
                    sorted_products]
    return jsonify({
        'total_pages': (total_records + per_page - 1) // per_page,
        'current_page': page,
        'productsList': productsList,
    })


# 相似商品
@bp.route("/contentRecs", methods=['POST'])
def contentRecs():
    # 获取参数
    data = request.get_json()
    product_id = int(data.get("product_id"))
    recs = ContentBasedProductRecs.query.filter_by(product_id=product_id).first()
    productIdList = [x["product_id"] for x in recs.recommendations]
    # 查询商品信息
    productsList = ProductModel.query.filter(ProductModel.product_id.in_(productIdList)).all()
    # 转字典之后json
    productsList = [{k: v for k, v in product.__dict__.items() if k != '_sa_instance_state'} for product in
                    productsList]
    return jsonify({"productsList": productsList})


# 为您推荐
@bp.route("/userRecs", methods=['POST'])
@login_required
def userRecs():
    user_id = g.user.user_id
    recs = AlsUserRecsModel.query.filter_by(user_id=user_id).first()
    # 用户还没评分，还没生成数据
    if recs is None:
        # 获取参数
        data = request.get_json()
        product_id = int(data.get("product_id"))
        recs = ItemCFProductRecsModel.query.filter_by(product_id=product_id).first()
        productIdList = [x["product_id"] for x in recs.recommendations]
        # 查询商品信息
        productsList = ProductModel.query.filter(ProductModel.product_id.in_(productIdList)).all()
        # 转字典之后json
        productsList = [{k: v for k, v in product.__dict__.items() if k != '_sa_instance_state'} for product in
                        productsList]
        return jsonify({"productsList": productsList})
    else:
        productIdList = [x["product_id"] for x in recs.recommendations]
        # 查询商品信息
        productsList = ProductModel.query.filter(ProductModel.product_id.in_(productIdList)).all()
        # 转字典之后json
        productsList = [{k: v for k, v in product.__dict__.items() if k != '_sa_instance_state'} for product in
                        productsList]
        return jsonify({"productsList": productsList})
